package com.ohs.ohsoa.system.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ohs.ohsoa.system.entity.GroupEnterprise;
import com.ohs.ohsoa.system.entity.Subgroup;
import com.ohs.ohsoa.system.entity.SubgroupAndUserRelation;
import com.ohs.ohsoa.system.entity.UserInfo;
import com.ohs.ohsoa.system.mapper.SubgroupMapper;
import com.ohs.ohsoa.system.vo.SubgroupRequestBean;
import com.ohs.ohsoa.system.vo.SubgroupUserInfoVo;
import com.ohs.ohsoa.system.vo.SubgroupVo;
import com.ohs.ohsoa.system.vo.TreeVo;
import com.ohs.ohsoa.utils.IsNull;
import com.ohs.ohsoa.utils.bean.requestBean.PageParam;
import com.ohs.ohsoa.utils.exception.BizException;

/**
 * Subgroup小组设置
 *
 * @author mwx
 * @since  2021年9月22日
 */
@Service
public class SubgroupServiceImpl extends ServiceImpl<SubgroupMapper, Subgroup> implements SubgroupService {

    @Resource
    private SubgroupMapper subgroupMapmper;


    @Resource
    private MessageSource messageSource;

    /**
     * 分页查询
     *
     * @param pageParam 检索用参数
     * @return listSubgroup
     * @author mwx
     * @since  2021年9月22日
     */
    @Override
    public List<SubgroupVo> listSubgroup(PageParam<Subgroup> pageParam) {
        // 获取subgroup对象
        Subgroup subgroup = pageParam.getSearchbean();
        // 分页
        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
        // 获取并返回subgroup集合
        return subgroupMapmper.listSubgroup(subgroup);
    }

    /**
     * 员工查询
     *
     * @param pageParam 检索用参数
     * @return listUserInfo
     * @author mwx
     * @since  2021年9月24日
     */
    @Override
    public List<SubgroupUserInfoVo> listUserInfo(PageParam<UserInfo> pageParam) {
        UserInfo userInfo = pageParam.getSearchbean();
        // 分页
        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
        // 获取并返回subgroup集合

        return subgroupMapmper.listUserInfo(userInfo);
    }

    /**
     * 员工树
     *
     * @return listUserInfo
     * @author mwx
     * @since  2021年9月24日
     */
    @Override
    public List<TreeVo> treeUserInfo() {
        // 获取集团list
        List<TreeVo> treeUserInfo = subgroupMapmper.listGroupEnterprise();
        if (IsNull.isNull(treeUserInfo)) {
            treeUserInfo = new ArrayList<>();
            return treeUserInfo;
        }

        for (TreeVo treeResponseBean : treeUserInfo) {
            // 获取部门list
            List<TreeVo> listDepartment = subgroupMapmper.listDepartment(treeResponseBean.getId());
            if (IsNull.isNull(listDepartment)) {
                listDepartment = new ArrayList<>();
            }
            for (TreeVo department : listDepartment) {
                // 获取员工list
                List<TreeVo> listUserInfo = subgroupMapmper.listUser(department.getId(),null);
                if (IsNull.isNull(listUserInfo)) {
                    listUserInfo = new ArrayList<>();
                } else {
                    listUserInfo.stream().forEach(u -> {
                        u.setChildren(new ArrayList<>());
                    });
                }
                department.setChildren(listUserInfo);
            }
            treeResponseBean.setChildren(listDepartment);

        }
        return treeUserInfo;
    }

    /**
     * 新增数据
     *
     * @param subgroup "实例对象"
     * @return 1为成功
     * @author mwx
     * @since  2021年9月22日
     */
    @Override
    @Transactional
    public void insertSubgroup(SubgroupRequestBean subgroup) {

        String subgroupGuid = UUID.randomUUID().toString().replace("-", "");
        subgroup.setSubgroupGuid(subgroupGuid);

        //判断小组名称是否重复
        Boolean flg = noSameGroupName(subgroup.getSubgroupGuid(), subgroup.getGroupEnterpriseGuid(), subgroup.getSubgroupName());
        if (!flg){
            throw new BizException("E0003", messageSource.getMessage("E0003",new String[] {"グループ名称","グループ名称"}, null)) ;
        }

        subgroupMapmper.insertSubgroup(subgroup);
        if (subgroup.getListSubgroupAndUserRelation() != null) {
            subgroup.getListSubgroupAndUserRelation().stream().forEach(subgroupAndUserRelation -> {
                subgroupAndUserRelation.setSURGuid(UUID.randomUUID().toString().replace("-", ""));
                subgroupAndUserRelation.setSubgroupGuid(subgroupGuid);
                subgroupMapmper.insertSubgroupAndUserRelation(subgroupAndUserRelation);
            });
        }
    }

    /**
     * 小组详情成员查询
     *
     * @param pageParam 检索用参数
     * @return listUserInfo
     * @author mwx
     * @since  2021年9月24日
     */
    @Override
    public List<SubgroupAndUserRelation> listSubgroupAndUserRelation(PageParam<SubgroupAndUserRelation> pageParam) {
        String subgroupGuid = pageParam.getSearchbean().getSubgroupGuid();
        // 分页
        PageHelper.startPage(pageParam.getIndexPage(), pageParam.getPageSize());
        // 获取并返回subgroup集合

        return subgroupMapmper.listSubgroupAndUserRelation(subgroupGuid);
    }

    /**
     * 修改数据
     *
     * @param subgroup "实例对象"
     * @return 1为成功
     * @author mwx
     * @since  2021年9月24日
     */
    @Override
    @Transactional
    public void updateSubgroup(SubgroupRequestBean subgroup) {
        //判断小组名称是否重复
        Boolean flg = noSameGroupName(subgroup.getSubgroupGuid(), subgroup.getGroupEnterpriseGuid(), subgroup.getSubgroupName());
        if (!flg){
            throw new BizException("E0003", messageSource.getMessage("E0003",new String[] {"グループ名称","グループ名称"}, null)) ;
        }

        subgroupMapmper.deleteSubgroupAndUserRelationById(subgroup.getSubgroupGuid());
        subgroupMapmper.updateSubgroup(subgroup);
        if (subgroup.getListSubgroupAndUserRelation() != null) {
            subgroup.getListSubgroupAndUserRelation().stream().forEach(subgroupAndUserRelation -> {
                subgroupAndUserRelation.setSURGuid(UUID.randomUUID().toString().replace("-", ""));
                subgroupAndUserRelation.setSubgroupGuid(subgroup.getSubgroupGuid());
                subgroupMapmper.insertSubgroupAndUserRelation(subgroupAndUserRelation);
            });
        }
    }

    /**
     * 批量删除数据
     *
     * @param  ids "listId"
     * @return 1为成功
     * @author mwx
     * @since  2021年9月24日
     */
    @Override
    @Transactional
    public void deleteSubgroupById(List<String> ids) {
        subgroupMapmper.deleteSubgroupById(ids);
        subgroupMapmper.deleteSubgroupAndUserRelationByIds(ids);
    }

    @Override
    public TreeVo treeUserInfoByGroupEnterpriseGuid(String groupEnterpriseGuid) {
        return this.getTreeUserInfoByGroupEnterpriseGuid(groupEnterpriseGuid,null);
    }

    @Override
    public TreeVo treeUserInfoByGroupEnterpriseGuidExceptLogin(UserInfo userInfo) {
        return this.getTreeUserInfoByGroupEnterpriseGuid(userInfo.getGroupEnterpriseGuid(),userInfo.getUserinfoGuid());
    }

    private TreeVo getTreeUserInfoByGroupEnterpriseGuid(String groupEnterpriseGuid, String userinfoGuid) {
        TreeVo treeVo = new TreeVo();
        treeVo.setId(groupEnterpriseGuid);
        GroupEnterprise groupEnterprise =subgroupMapmper.getGroupEnterprise(groupEnterpriseGuid);
        treeVo.setName(groupEnterprise.getEnterpriseName());
        // 获取部门list
        List<TreeVo> listDepartment = subgroupMapmper.listDepartment(groupEnterpriseGuid);
        if (IsNull.isNull(listDepartment)) {
            listDepartment = new ArrayList<>();
        }

        Iterator<TreeVo> iterator = listDepartment.iterator();
        while (iterator.hasNext()) {
            // 获取员工list
            TreeVo department = iterator.next();
            List<TreeVo> listUserInfo = subgroupMapmper.listUser(department.getId(),userinfoGuid);

            if (IsNull.isNull(listUserInfo)) {
                iterator.remove();
                continue;
            } else {
                listUserInfo.stream().forEach(u -> {
                    u.setChildren(new ArrayList<>());
                });
            }
            department.setChildren(listUserInfo);
        }
        treeVo.setChildren(listDepartment);

        return treeVo;
    }

    /**
     * 判断小组名称是否重复
     * @param subgroupGuid 小组id
     * @param groupEnterpriseGuid 企业id
     * @param subgroupName 小组名称
     * @return 是否重复
     */
    public Boolean noSameGroupName(String subgroupGuid, String groupEnterpriseGuid, String subgroupName){

        // 定义返回值
        boolean flg = false;

        QueryWrapper<Subgroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_enterprise_guid", groupEnterpriseGuid)
                    .eq("subgroup_name", subgroupName)
                    .ne("subgroup_guid", subgroupGuid);

        if (this.count(queryWrapper) == 0){
            flg = true;
        }
        return flg;
    }



}
